How to encrypt passwords in PHP/Node.JS/Python
Regardless of what language you use, Bcrypt provides a secure way to store encrypted passwords for just about any online system today.
Bcrypt was first presented in 1999 and uses Blowfish as the cipher. You can also specify an iteration count to make it slower, but even more resistant to brute-force and dictionary attacks.
While Scrypt is newer, and slower, which in theory will make dictionary attacks much slower, Bcrypt is much older and has stood up to much more public scrutiny than Scrypt over the years.
Lastly, there is Argon2 which won the password hashing challenge (PHC) in 2015. The idea being as technology advanced in the realms of ASIC and GPU computation, older methods showed potential signs of weakness.
Argon2 aims to address this by making the memory and computational requirements even more expensive than Scrypt and of course Bcrypt.
Despite these newer hashing algorithms, I have focused on Bcrypt purely because of its age and reputation as a strong, well-scrutinized password hashing algorithm for encrypting your database passwords.
Below we will look at how to encrypt and hash passwords in three common development languages, as well as how to validate a user-input password against a password hash stored in your database.
In all the examples we will use a cost factor of 10. Unfortunately, the ideal cost factor will differ depending on your servers processing power so providing a single value isn’t possible.
Feel free to play around while timing the functions to determine what works best for you.
How to encrypt passwords in PHP
As of PHP 5.5.0, there are built-in password hashing functions which specifically use the secure Bcrypt hashing function. Gone are the days of when you had to manually manage the hashing and salting of passwords.
How to encrypt passwords in Node.JS
Hashing passwords in Node.JS is a breeze thanks to the Bcrypt NPM module. Just install the module using npm.
Once the Bcrypt module is installed you can hash passwords with just a few lines of code.
There are also synchronous versions available if you don’t wish to use asynchronous callbacks.
How to encrypt passwords in Python
And last but not least, we have Bcrypt usage in Python. As with Node.JS, we have to first install a module to use in Python.
But once available, it’s again very easy to hash passwords in Python, as with the other languages.
Related Articles
We look at a simple way to determine the Node.JS version from code to ensure all your requirements are met.
How to lazy load images in React using react-lazy-load-image-component
Start Creating Freedom today
Learn to build fast, scalable SaaS as I document my journey towards freedom. Follow along for real-world lessons and insights from my experiences.